package com.iye.puretennis.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.custom.UserInfoFragment;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserInfo;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.pulltorefresh.library.PullToRefreshBase;
import com.iye.puretennis.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/19.
 */
public class MyFriendsFragment extends TabFragment {

    public static String TAG = "my_friends";

    private PullToRefreshListView friendsView;

    private List<UserInfo> friends = new ArrayList<UserInfo>();

    private FriendsAdapter friendsAdapter;

    @Override
    public void onCustomCreateView(LayoutInflater inflater) {
        friendsView = (PullToRefreshListView) mainView.findViewById(R.id.my_friends_list);

        final ImageButton addButton = (ImageButton) mainView.findViewById(R.id.add_button);


        View.OnClickListener buttonClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goFragment(getSourceId(), SearchFriendFragment.TAG, SearchFriendFragment.class, null, false);
            }
        };

        addButton.setOnClickListener(buttonClickListener);

        friendsAdapter = new FriendsAdapter(getActivity(), R.layout.myfriend_item);

        friendsView.setAdapter(friendsAdapter);

        friendsView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                updateUI();
            }
        });
    }


    @Override
    public int getViewId() {
        return R.layout.myfriends;
    }

    @Override
    public int getSourceId() {
        return R.id.my_friends;
    }

    @Override
    public void updateUI() {

        friendsListRender(token);
    }

    private void friendsListRender(final UserToken token) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                json = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS), token.getToken());
                getActivity().runOnUiThread(uiFriendsUpdate);
            }
        }).start();
    }

    private class FriendsAdapter extends BaseAdapter {
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private FriendItemViewCache viewCache;

        FriendsAdapter(Context context, int resource) {
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return friends.size();
        }

        @Override
        public Object getItem(int position) {
            return friends.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HuaWenHuPoTextView nameView;

            ImageView photoView;

            ImageButton requestButton;

            if (convertView == null) {//第一次渲染页面
                convertView = inflater.inflate(resource, null);
                nameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.my_friend_item_name);
                photoView = (ImageView) convertView.findViewById(R.id.user_photo);
                requestButton = (ImageButton) convertView.findViewById(R.id.my_friend_item_action_details);
                viewCache = new FriendItemViewCache();
                viewCache.nameTextView = nameView;
                viewCache.photoView = photoView;
                viewCache.requestButton = requestButton;
                convertView.setTag(viewCache);

            } else {
                viewCache = (FriendItemViewCache) convertView.getTag();
                nameView = viewCache.nameTextView;
                photoView = viewCache.photoView;
                requestButton = viewCache.requestButton;
            }
            final UserInfo friend = friends.get(position);
            nameView.setText(friend.getNickname(token.getGuid()));

            final String friendGuid = friend.getGuid();

            loadUserImage(friendGuid, photoView);

            final boolean friendRequest = friend.isRequest();
            if (friendRequest) {
                requestButton.setVisibility(View.VISIBLE);
            } else {
                requestButton.setVisibility(View.INVISIBLE);
            }

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Session session = Session.newSession();
                    session.put("userGuid", friendGuid);
                    goFragment(getSourceId(), UserInfoFragment.TAG, UserInfoFragment.class, null, false);
                }
            });

            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showPopupMenu(view, friendRequest ? R.menu.details_accept_reject_menu : R.menu.details_delete_menu, new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
                            int menuItemId = menuItem.getItemId();
                            if (menuItemId == R.id.accept_menu) {
                                acceptInvitation(friend);
                            } else if (menuItemId == R.id.reject_menu) {
                                rejectInvitation(friend);
                            } else {
                                deleteFriend(friend);
                            }
                            return true;
                        }
                    });


                    return true;
                }
            });
            return convertView;
        }

        private class FriendItemViewCache {
            private HuaWenHuPoTextView nameTextView;
            private ImageView photoView;
            private ImageButton requestButton;
        }
    }

    private Runnable uiFriendsUpdate = new Runnable() {
        @Override
        public void run() {
            if (!Constant.RESPONSE_BADLY.equals(json)) {
                try {
                    friends.clear();//remove old data

                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray friendsJsonArray = jsonObject.getJSONArray("friends");
                    JSONArray requestsJsonArray = jsonObject.getJSONArray("requests");
                    for (int j = 0; j < requestsJsonArray.length(); j++) {
                        JSONObject requestObj = requestsJsonArray.getJSONObject(j);
                        String requestGuid = requestObj.getString("guid");
                        JSONObject userObj = requestObj.getJSONObject("sender");
                        String guid = userObj.getString("guid");
                        String name = userObj.getString("nickname");
                        String imageBase64Byte = userObj.getString("imageBase64Byte");
                        friends.add(new UserInfo(guid, name, imageBase64Byte, requestGuid, true));
                    }

                    for (int i = 0; i < friendsJsonArray.length(); i++) {
                        JSONObject friendObj = friendsJsonArray.getJSONObject(i);
                        String guid = friendObj.getString("guid");
                        String name = friendObj.getString("name");
                        friends.add(new UserInfo(guid, name, null, true));
                    }

                    friendsAdapter.notifyDataSetChanged();
                    friendsView.onRefreshComplete();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private void deleteFriend(final UserInfo friend) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_DELETE) + "/" + friend.getGuid(), token.getToken());
                if (!Constant.RESPONSE_BADLY.equals(result)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            friends.remove(friend);
                            friendsAdapter.notifyDataSetChanged();
                        }
                    });
                }

            }
        }).start();
    }

    private void rejectInvitation(final UserInfo friend) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_REQUEST_REJECT) + "?guid=" + friend.getRequestGuid(), token.getToken());
                if (!Constant.RESPONSE_BADLY.equals(result)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            friends.remove(friend);
                            friendsAdapter.notifyDataSetChanged();
                        }
                    });
                }

            }
        }).start();
    }

    private void acceptInvitation(final UserInfo friend) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.FRIENDS_REQUEST_ACCEPT) + "/" + friend.getGuid(), token.getToken());
                if (!Constant.RESPONSE_BADLY.equals(result)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            friends.remove(friend);
                            friends.add(new UserInfo(friend.getGuid(), friend.getNickname(token.getGuid()), friend.getImageBase64Byte(), friend.isUploadImage()));
                            friendsAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }).start();
    }


}
